package com.changgou.service.goods.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changgou.goods.pojo.Category;
import com.changgou.goods.pojo.Spec;
import com.changgou.service.goods.dao.SpecMapper;
import com.changgou.service.goods.service.CategoryService;
import com.changgou.service.goods.service.SpecService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SpecServiceImpl extends ServiceImpl<SpecMapper, Spec> implements SpecService {

    @Resource
    private CategoryService categoryService;

    @Override
    public List<Map> findListByCategroyName(String category) {

//        先去查找 商品表中的 template_id
        QueryWrapper<Category> wrapper = new QueryWrapper<Category>().eq("name", category);

        Category category1 = this.categoryService.getOne(wrapper);
        if(ObjectUtil.isEmpty(category1)){
            return null;
        }
//        查找到之后，根据template_id 去查询 spec 表
        List<Spec> specs = this.lambdaQuery().eq(Spec::getTemplateId, category1.getTemplateId())
                .list();
        if(ObjectUtil.isEmpty(specs)){
            return null;
        }

//        找到了，遍历。转换。
     List<Map> specList = new ArrayList<>(specs.size());
        specs.forEach(spec -> {
            String[] options = StrUtil.splitToArray(spec.getOptions(), ",");
            specList.add(MapUtil.of("options",options));
        });


        return specList;
    }
}
